package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.entity.Notification;
import com.blog.mapper.NotificationMapper;
import com.blog.service.NotificationService;
import com.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification> implements NotificationService {

    @Override
    public Page<Notification> getUserNotifications(Long userId, Integer pageNum, Integer pageSize) {
        Page<Notification> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        //根据未读状态显示通知
        queryWrapper.eq(Notification::getUserId, userId)
                .eq(Notification::getStatus, 0);
        queryWrapper.orderByDesc(Notification::getCreateTime);

        return this.page(page, queryWrapper);
    }

    @Override
    public Integer getUnreadCount(Long userId) {
        return this.baseMapper.selectUnreadCount(userId);
    }

    @Override
    @Transactional
    public boolean markAsRead(Long notificationId, Long userId) {
        Notification notification = this.getById(notificationId);
        if (notification == null || !notification.getUserId().equals(userId)) {
            return false;
        }

        notification.setStatus(1); // 标记为已读
        return this.updateById(notification);
    }

    @Override
    @Transactional
    public boolean markAllAsRead(Long userId) {
        return this.baseMapper.markAllAsRead(userId) > 0;
    }

    @Override
    @Transactional
    public boolean createNotification(Notification notification) {
        return this.save(notification);
    }
}
